import React  from 'react';
import {message,Icon,Button,Input,Card,Table,Dropdown,Menu,Modal,Form,DatePicker,Upload} from 'antd';
import styles from '../style/PropertyDataDetailInfo.scss';
const ButtonGroup = Button.Group;
import api from 'container/api';
import moment from 'moment';

import {
  ASSET_LEVEL,
  IS_NOT,
  GUARANTEE,
  TRANSPORT_TYPE,
  RETURNED_MONEY_WAY,
  RETURNED_MONEY_SOURCE,
  REMARK_TYPE
} from 'constants/index';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 17 },
};
const formTailLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 8, offset: 4 },
};

//发票信息
class ReceiptInfo extends React.Component {

  constructor(props){
    super(props);
    let {id} = props;
    this.state ={
      id,
      dataSource:[],
      footerData:{},
      editModal:false,
      detail:{files:[]},
      isDetail:false,
      upload:{
        loading:false,
      },
    }
  }

  componentWillMount(){
    this.doFetch()
  }

  async doFetch(){
    let {id} = this.state;
    let result  = await api('/assets/receipt/list' ,{id});
    if(!result.success){
      message.error(result.message);
      return
    }
    let data = result.data;
    this.setState({
      dataSource:data.item_list,
      footerData:{
        total_amount:data.total_amount,
        total_money:data.total_money
      }
    })
  }


  handleMenuClick(record,e){
    switch (e.key){
      case 'edit':
        this.openFormModal(record.id);
        break;
      case 'delete':
        Modal.confirm({
          title: '提示',
          content: '您确认删除该记录？',
          onOk:this.deleteById.bind(this,record.id),
        })
        break;
    };
  }

  async deleteById(id){
    let result = await api('/assets/receipt/delete' ,{id});
    if(!result.success){
      message.error(result.message);
      return
    }
    message.success('操作成功' ,1 , () => {
      this.doFetch();
    })
  }

  renderTableFooter = () => {
    let {footerData} = this.state;
    return (
      <div>
        票面吨数：{footerData.total_amount}吨 <span className="ant-divider" />
        发票金额：{footerData.total_money}元
      </div>
    )
  }

  async openFormModal(id){
    let {detail} = this.state;
    if(!id){
      this.setState({editModal:true})
      return
    }
    let result = await api('/assets/receipt/detail' ,{id});
    if(!result.success){
      message.error(result.message);
      return
    }
    result.data.files =  result.data.files.map((item,index) => {
      return {
           uid: Math.random().toString(36).slice(2),      
           name: item.name,
           status: 'done', 
           type:item.type,
           url:item.url,
        }
    })
    this.props.form.setFieldsValue({files:result.data.files})
    this.setState({
      editModal:true,
      detail:result.data
    })
    
  }

  //弹出确定
  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (err) return;
      this.save({...values})
    });

  }
  async save(values) {
    let {detail} = this.state;
    values.date = values.date.format('YYYY-MM-DD');
    values.asset_id = this.state.id;
    if(detail.id){
      values.id = detail.id;
    }
    let result = await api('/assets/receipt/edit' ,values);
    if(!result.success){
      message.error(result.message);
      return
    }

    message.success('保存成功' , 1, () => {
      this.setState({editModal:false},() =>{
        this.doFetch()
      })
    })
  }
  //取消弹出
  handleCancel = () =>{
    this.setState({
      editModal:false,
      detail:{},
      isDetail:false
    })
    this.props.form.resetFields();
  }
  uuid(){
    return Math.random().toString(36).slice(2);
  }

  uploadProps = () => {
    let _this = this;
    let {detail,isDetail} = this.state;
    return {
      customRequest:async ({ file, fileList }) => {
        let {defaultFileList=[]} = this.state;
        let result = await api.upload('/file/upload?file_type=4',file);
        if(result){
          let uid = this.uuid();
          detail.files.push({
            name:file.name,
            url:result.data.url,
            type:result.data.type,
            uid:uid,
            status:'done'
          })
        }
        this.props.form.setFieldsValue({
          files:detail.files
        })
        this.setState({detail})
      },
      onRemove:(file) => {
        return !isDetail
      }
    }
  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  render(){
    let {dataSource,detail,isDetail} = this.state;
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    let modalProps = {};
    if(isDetail){
      modalProps.footer = null;
      modalProps.title = '发票详情'
    }
    return (
      <div>
        <Card 
          title="发票信息" 
          bordered={false} 
          bodyStyle={{backgroundColor:'#fff',padding:'0'}}
          extra={
            <a href='javascript:void 0;' className={styles.cardExtraA} onClick={this.openFormModal.bind(this,null)}>
            <Icon style={{ fontSize: 18}} type="plus-circle-o" />
            </a>
          }
        >
          <Table
            size='small' 
            columns={this.getColumns()} 
            dataSource={dataSource} 
            rowKey={(record,index) => index}
            pagination={false}
            footer={this.renderTableFooter}
          />
        </Card>
        <Modal
          title="添加发票"
          visible={this.state.editModal}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={400}
          wrapClassName={"modal-from"}
          maskClosable={false}
          {...modalProps}
        >
          <Form 
            layout="horizontal" 
          >
            <Form.Item
              label="发票日期"
              {...formItemLayout}

            >
              {getFieldDecorator('date', {
                rules: [{ required: true, message: '请选择发票日期' }],
                initialValue:detail.date?moment(detail.date):null
              })(
                <DatePicker style={{width:"100%"}} />
              )}
            </Form.Item>
            <Form.Item
              label="发票号码"
              {...formItemLayout}
            >
              {getFieldDecorator('number', {
                rules: [{ required: true, message: '请输入发票号码' }],
                initialValue:detail.number
              })(
                <Input  placeholder="请输入发票号码" />
              )}
            </Form.Item>
            <Form.Item
              label="票面吨数"
              {...formItemLayout}
            >
              {getFieldDecorator('amount', {
                rules: [{ required: true, message: '请输入票面吨数' }],
                initialValue:detail.amount
              })(
                <Input  placeholder="请输入票面吨数" addonAfter="吨"/>
              )}
            </Form.Item>
            <Form.Item
              label="税价合计"
              {...formItemLayout}
            >
              {getFieldDecorator('money', {
                rules: [{ required: true, message: '请输入税价合计' }],
                initialValue:detail.money
              })(
                <Input  placeholder="请输入税价合计" addonAfter="元" />
              )}
            </Form.Item>
            <Form.Item
              label="发票文件"
              {...formItemLayout}
            >
              {getFieldDecorator('files', {
                rules: [{ required: false, message: '请上传发票文件' }],
                valuePropName: 'fileList',
                getValueFromEvent: this.normFile,
                initialValue:detail.files
              })(
                <Upload {...this.uploadProps()}>
                  {isDetail?null
                    :<Button loading={this.state.upload.loading}>
                      <Icon type="upload" /> 点击上传
                    </Button>
                  }
                </Upload>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }

  getColumns(){
    let columns = [
      {
        title: '发票日期',
        dataIndex: 'date',
        key: 'date'
      }, 
      {
        title: '票号',
        dataIndex: 'number',
        key: 'number',
      }, 
      {
        title: '票面吨数（吨）',
        dataIndex: 'amount',
        key: 'amount',
      }, 
      {
        title: '票面价税合计',
        dataIndex: 'money',
        key: 'money',
      },
      {
        title: '发票',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '操作',
        key: 'action',
        width:100,
        render: (text, record) => (
          <ButtonGroup>
            <Button onClick={() => {
              this.setState({isDetail:true} ,() => {
                this.openFormModal(record.id)
              })
            }}>详情</Button>
            <Dropdown 
              placement="bottomRight"
              overlay={
                <Menu onClick={this.handleMenuClick.bind(this,record)}>
                  <Menu.Item key="edit">编辑信息</Menu.Item>
                  <Menu.Item key="delete">删除记录</Menu.Item>
                </Menu>
              }
            >
            <Button  icon="bars" />
            </Dropdown>
          </ButtonGroup>
        ),
      }]
    return columns;
  }
}

export default Form.create()(ReceiptInfo);
